package ru.compft.common.dao.impl;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Repository;
import ru.compft.common.dao.PermissionDao;
import ru.compft.common.data.AppPermission;
import ru.compft.common.data.meta.PermissionProperty;

import javax.annotation.Resource;
import java.util.List;

/**
 * User: ASUS
 * Date: 27.10.12
 * Time: 0:12
 * DAO работы с правами доступа пользователя
 */
@Repository
public class PermissionDaoImpl implements PermissionDao {
    private static final Logger logger = LoggerFactory.getLogger(PermissionDaoImpl.class);

    @Resource(name = "sessionFactory")
    private SessionFactory sessionFactory;

    @Override
    public List<AppPermission> getAllPermissions() {
        Session session = sessionFactory.getCurrentSession();
        Criteria criteria = session.createCriteria(AppPermission.class);

        return criteria.list();
    }

    @Override
    public List<AppPermission> getPermissions(int from, int count) {
        Session session = sessionFactory.getCurrentSession();
        Criteria criteria = session.createCriteria(AppPermission.class)
                .setFirstResult(from)
                .setMaxResults(count);

        return criteria.list();
    }

    @Override
    public int countAllPermissions() {
        Session session = sessionFactory.getCurrentSession();
        Criteria criteria = session.createCriteria(AppPermission.class)
                .setProjection(Projections.rowCount());

        final Object result = criteria.uniqueResult();
        return result != null ? Integer.parseInt(result.toString()) : 0;
    }

    @Override
    public AppPermission getPermissionById(Long id) {
        Session session = sessionFactory.getCurrentSession();
        return (AppPermission) session.get(AppPermission.class, id);
    }

    @Override
    public AppPermission getPermissionByCode(String code) {
        Session session = sessionFactory.getCurrentSession();
        Criteria criteria = session.createCriteria(AppPermission.class)
                .add(Restrictions.like(PermissionProperty.code, code));

        return (AppPermission) criteria.uniqueResult();
    }

    @Override
    public boolean createPermission(AppPermission appPermission) {
        sessionFactory.getCurrentSession().persist(appPermission);
        return appPermission.getId() != null;
    }

    @Override
    public AppPermission update(AppPermission permission) {
        return (AppPermission) sessionFactory.getCurrentSession().merge(permission);
    }
}
